'''
Classes for dealing with mapping refs onto other refs.

Created on 2011-07-05

@author: Andrew Roth
'''
import csv

cdef class RefMapBaseCounter(Counter):
    '''
    Wrapper class around counter which maps the reference in the bam file onto another set of names defined by ref_map which
    is a lookup dictionay.
    
    For example ref_map = {'chr1' : '1'}
    '''
    
    def __init__(self, Counter counter, dict ref_map):
        self._counter = counter
        
        self._ref_map = ref_map
        
        self._reverse_map = dict(zip(ref_map.values(), ref_map.keys()))
        
        refs = []
        for ref in self._counter.refs:
            if ref not in ref_map:
                continue
            else:
                refs.append(ref_map[ref])
        
        self._refs = tuple(sorted(refs))
        
    def iter_ref(self, ref):
        '''
        Expects mapped ref value as argument.
        '''
        iter = self._counter.iter_ref(self._reverse_map[ref])
        
        return iter
    
def load_ref_map(file_name, delimiter_char='\t'):
    reader = csv.reader(open(file_name), delimiter=delimiter_char)
    
    ref_map = {}
    
    for row in reader:
        ref_map[row[1]] = row[0]
    
    return ref_map    
